<template>
  <el-dialog
    :title="title"
    :visible.sync="localVisible"
    width="60%"
    append-to-body
    :close-on-click-modal="false"
    @close="handleCancel"
  >
    <el-form ref="form" :model="form" :rules="computedRules" label-width="140px">
      <el-divider content-position="center">合同信息</el-divider>
      <el-row :gutter="20" style="margin-top: 3%">
        <el-col :span="12">
          <el-form-item label="项目类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择项目类型"
              filterable
              style="width: 100%"
              @change="$emit('type-change', $event)"
            >
              <el-option
                v-for="item in dict.type.project_types"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="合同录入时间"
            prop="recordTime"
            style="width: 100%"
          >
            <el-date-picker
              v-model="form.recordTime"
              type="date"
              placeholder="请输入录入时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="合同编号"
            prop="no"
            style="width: 100%;"
          >
            <el-input
              v-model="form.no"
              clearable
              placeholder="请输入合同编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="合同签订时间"
            prop="signTime"
            style="width: 100%"
          >
            <el-date-picker
              v-model="form.signTime"
              type="date"
              placeholder="请输入签订时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="form.projectName"
              placeholder="请输入项目名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区（县）" prop="region">
            <el-input v-model="form.region" placeholder="请输入区（县）" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="12">
          <el-form-item label="业主单位" prop="organizationName">
            <el-input
              v-model="form.organizationName"
              placeholder="请输入业主单位"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="勘察设计公司" prop="company">
            <el-input v-model="form.company" placeholder="请输入勘察设计公司" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同金额（万元）" prop="money">
            <el-input-number
              v-model="form.money"
              controls-position="right"
              :min="0"
              :step="1"
              placeholder="请输入合同金额（万元）"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" style="">
          <el-form-item label="是否为特殊合同">
            <el-switch
              v-model="form.isSpec"
              style="display: block; margin-top: 1.4%"
              active-color="#13ce66"
              inactive-color="#409eff"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="form.isSpec">
        <el-col :span="24">
          <el-form-item label="部门特殊比列系数" prop="deptSpecRate">
            <el-input-number
              v-model="form.deptSpecRate"
              controls-position="right"
              :min="0"
              :step="0.01"
              :max="1"
              placeholder="请输入特殊比列系数"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="form.isSpec">
        <el-form-item
          label="市场拓展人员特殊比列系数"
          prop="expansionUserSpecRate"
        >
          <el-input-number
            v-model="form.expansionUserSpecRate"
            controls-position="right"
            :min="0"
            :step="0.01"
            :max="1"
            placeholder="请输入特殊比列系数"
          />
        </el-form-item>
      </el-row>
      <el-divider v-if="reviseSection" content-position="center">设计责任部门</el-divider>
      <el-row v-if="reviseSection" :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="项目设总"
            prop="projectDesignLeadUserId"
            style="width: 100%"
          >
            <el-select
              v-model="form.projectDesignLeadUserId"
              placeholder="请选择项目设总"
              multiple
              filterable
              clearable
              style="width: 100%"
              @change="handleUserIdChange"
            >
              <el-option
                v-for="item in userListWithNone"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="生产部门"
            prop="projectDesignLeadDeptIds"
            style="width: 100%"
          >
            <el-select
              v-model="form.projectDesignLeadDeptIds"
              multiple
              filterable
              placeholder="请选择生产部门"
              style="width: 100%"
              @change="handleDeptIdsChange"
            >
              <el-option
                v-for="item in deptListWithNone"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="item in selectProjectDesignDeptRateList" :key="item.deptId">
        <el-form-item
          :label="item.deptName"
          :prop="'design' + item.deptId"
          style="width: 50%"
        >
          <el-input-number
            v-model="item.rate"
            controls-position="right"
            :min="0"
            :step="0.01"
            :max="1"
            :placeholder="`请输入${item.deptName}比例`"
          />
        </el-form-item>
      </el-row>
      <el-divider content-position="center">各部门承接合同应分配</el-divider>
      <el-row :gutter="20">
        <el-form-item label="分配比例" prop="deptRateList">
          <el-col v-for="dept in deptRateList" :key="dept.deptId" :span="6">
            <div style="margin-bottom: 3%">
              <div style="border: #dcdfe6 solid 1px; text-align: center">
                {{ dept.deptName }}
              </div>
              <div style="width: 120px;">
                <el-switch
                  v-model="dept.isMoney"
                  style="display: block; margin-top: 2%"
                  active-color="#13ce66"
                  inactive-color="#409eff"
                  active-text="金额"
                  inactive-text="比例"
                />
              </div>
              <div v-show="dept.isMoney">
                <el-input-number
                  v-model="dept.money"
                  controls-position="right"
                  :min="0"
                  :step="0.01"
                  style="width: 160px;"
                />
              </div>
              <div v-show="!dept.isMoney">
                <el-input-number
                  v-model="dept.rate"
                  controls-position="right"
                  :min="0"
                  :step="0.01"
                  :max="1"
                  style="width: 160px;"
                />
              </div>
            </div>
          </el-col>
        </el-form-item>
      </el-row>
      <el-divider content-position="center">市场拓展应分配</el-divider>
      <el-row :gutter="20">
        <el-col :span="8" style="">
          <el-form-item label="分配方式" style="width: 270px">
            <el-switch
              v-model="form.isDept"
              style="display: block; margin-top: 2%"
              active-color="#13ce66"
              inactive-color="#409eff"
              active-text="按部门"
              inactive-text="按人"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            v-if="form.isDept"
            label="部门"
            prop="projectMarketExpansionDeptId"
          >
            <el-select
              v-model="form.projectMarketExpansionDeptId"
              placeholder="请选择部门"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in deptListWithNone"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="!form.isDept"
            label="人员"
            prop="projectMarketExpansionUserId"
          >
            <el-select
              v-model="form.projectMarketExpansionUserId"
              placeholder="请选择人员"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in userListWithNone"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="分配比列" prop="marketExpansionRate">
            <el-input-number
              v-model="form.marketExpansionRate"
              controls-position="right"
              :min="0"
              :step="0.01"
              :max="1"
              placeholder="请输入比例"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center">项目统筹人</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="人员" prop="projectCoordinatorId">
            <el-select
              v-model="form.projectCoordinatorId"
              placeholder="请选择人员"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in userListWithNone"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="分配比列" prop="projectCoordinatorRate">
            <el-input-number
              v-model="form.projectCoordinatorRate"
              controls-position="right"
              :min="0"
              :step="0.01"
              :max="1"
              placeholder="请输入比例"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="center">其他</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="是否待定" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.settlement_status"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        :disabled="!enableSubmit()"
        @click="submitForm"
      >确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addContract,
  updateContract
} from '@/api/settlement/contract'

export default {
  name: 'ContractFormDialog',
  props: {
    visible: { type: Boolean, required: true },
    title: { type: String, default: '' },
    userList: { type: Array, default: () => [] },
    deptList: { type: Array, default: () => [] },
    dict: { type: Object, required: true },
    editData: { type: Object, default: null }
  },
  data() {
    return {
      form: {},
      localVisible: false,
      rules: {
        no: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '合同类型不能为空', trigger: 'change' }
        ],
        recordTime: [
          { required: true, message: '录入时间不能为空', trigger: 'change' }
        ],
        projectName: [
          { required: true, message: '项目名称不能为空', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '区（县）不能为空', trigger: 'blur' }
        ],
        organizationName: [
          { required: true, message: '业主单位不能为空', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '勘察设计公司不能为空', trigger: 'blur' }
        ],
        money: [
          { required: true, message: '合同金额不能为空', trigger: 'blur' },
          { type: 'number', message: '合同金额必须是数字', trigger: 'blur' }
        ],
        signTime: [
          {
            required: true,
            message: '合同签订时间不能为空',
            trigger: 'change'
          }
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        projectMarketExpansionDeptId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ]
      },
      deptMap: new Map(),
      deptRateList: [],
      selectProjectDesignDeptRateList: [],
      reviseSection: true
    }
  },
  computed: {
    computedRules() {
      // 动态生成rules
      const rules = { ...this.rules }
      if (this.reviseSection) {
        rules.projectDesignLeadUserId = [
          { required: true, message: '请选择项目设总', trigger: 'change' }
        ]
      } else {
        rules.projectDesignLeadUserId = []
      }
      return rules
    },
    deptListToMap() {
      // 将部门列表转换为Map，便于快速查找
      this.deptMap.clear()
      this.deptList.forEach((dept) => {
        this.deptMap.set(dept.deptId, dept.deptName)
      })
      return this.deptMap
    },
    userListWithNone() {
      return [{ userId: '0', nickName: '暂无' }, ...this.userList]
    },
    deptListWithNone() {
      return [{ deptId: '0', deptName: '暂无' }, ...this.deptList]
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        this.localVisible = val
      }
    },
    localVisible(val) {
      if (!val) {
        this.$emit('update:visible', false)
      }
    },
    editData: {
      immediate: true,
      handler(val) {
        if (val) {
          // 用 Object.assign 保证响应式
          this.form = Object.assign({}, this.form, val)
          // 优先使用form.deptRateList的值，没有则用deptList渲染空数据
          const deptRateMap = (this.form.deptRateList || []).reduce((map, item) => {
            map[item.deptId] = item
            return map
          }, {})
          this.deptRateList = this.deptList.map(dept => {
            const rateItem = deptRateMap[dept.deptId]
            return {
              ...dept,
              rate: rateItem ? rateItem.rate : null,
              money: rateItem ? rateItem.money : null,
              isMoney: rateItem ? rateItem.isRate === 0 : false
            }
          })
          this.form.projectDesignLeadDeptIds = (val.projectDesignRateList || []).map(item => String(item.deptId))
          this.form.projectDesignLeadUserId = val.projectDesignLeadUserId && typeof val.projectDesignLeadUserId === 'string'
            ? val.projectDesignLeadUserId.split(',').filter(Boolean)
            : val.projectDesignLeadUserId || []
          this.selectProjectDesignDeptRateList = val.projectDesignRateList || []
        } else {
          this.form = {
            isDept: false,
            status: '1',
            projectDesignLeadUserId: [],
            projectDesignLeadDeptIds: []
          }
          this.deptRateList = this.deptList
          this.selectProjectDesignDeptRateList = []
        }
      }
    },
    'form.type': {
      immediate: true,
      handler(val) {
        // 监听form.type，等于'1'时reviseSection为false，否则为true
        this.reviseSection = val !== 1
      }
    }
  },
  methods: {
    enableSubmit() {
      if (
        !this.selectProjectDesignDeptRateList ||
        this.selectProjectDesignDeptRateList.length === 0
      ) {
        return true
      }
      for (let i = 0; i < this.selectProjectDesignDeptRateList.length; i++) {
        const rate = this.selectProjectDesignDeptRateList[i].rate
        if (!rate) {
          return false
        }
      }
      return true
    },
    submitForm() {
      this.form.signTime = this.form.signTime instanceof Date ? this.form.signTime.getTime() : this.form.signTime
      this.form.recordTime = this.form.recordTime instanceof Date ? this.form.recordTime.getTime() : this.form.recordTime
      this.form.isSpec = this.form.isSpec ? 1 : 0
      this.form.deptRateList = this.deptListToDeptRateList(this.deptRateList)
      this.form.projectDesignRateList = this.selectProjectDesignDeptRateList
      // 修正 projectDesignLeadDeptIds 处理，确保为数组再 join
      if (Array.isArray(this.form.projectDesignLeadDeptIds)) {
        this.form.projectDesignLeadDeptIds = this.form.projectDesignLeadDeptIds.join(',')
      }

      // 修正 projectDesignLeadUserId 处理，确保为数组再 join
      if (Array.isArray(this.form.projectDesignLeadUserId)) {
        this.form.projectDesignLeadUserId = this.form.projectDesignLeadUserId.join(',')
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const req = this.form.id ? updateContract(this.form) : addContract(this.form)
          req.then(() => {
            this.$emit('success')
          })
        }
      })
    },
    handleCancel() {
      // 清空 selectProjectDesignDeptRateList
      this.selectProjectDesignDeptRateList = []
      // 清空表单数据
      this.form = {
        isDept: false,
        status: '1',
        projectDesignLeadUserId: [],
        projectDesignLeadDeptIds: []
      }
      this.deptRateList = []
      this.$emit('cancel')
    },
    deptListToDeptRateList(deptList) {
      const deptRateList = []
      deptList.forEach((item) => {
        if (item.rate || item.money) {
          const deptRate = {
            deptId: item.deptId,
            rate: item.isMoney ? 0 : item.rate,
            money: item.isMoney ? item.money : 0,
            isRate: !item.isMoney ? 1 : 0
          }
          deptRateList.push(deptRate)
        }
      })
      return deptRateList
    },
    handleDeptIdsChange(newVal) {
      const oldList = this.selectProjectDesignDeptRateList || []
      console.log('🚀 ~ handleDeptIdsChange ~ this.selectProjectDesignDeptRateList :', this.selectProjectDesignDeptRateList)
      const newList = []
      newVal.forEach(deptId => {
        const exist = oldList.find(item => String(item.deptId) === deptId)
        const dept = this.deptList.find(d => d.deptId === deptId)
        newList.push({
          id: exist ? exist.id : undefined,
          deptId,
          deptName: dept ? dept.deptName : '',
          rate: exist ? exist.rate : undefined // 保持原有rate
        })
      })
      this.selectProjectDesignDeptRateList = newList
    },
    handleUserIdChange(newVal) {
      // 只保留必要逻辑，不再赋值
      // this.form.projectDesignLeadUserId = newVal
      // console.log('🚀 ~ handleUserIdChange ~ this.form.projectDesignLeadUserId :', this.userList[0])
    }
  }
}
</script>
